<?php
/**
 * @file
 *   Links the Facebook and Untold accounts of the current facebook user.
 */

require_once ("../utils/query.php");

session_start();
if(empty($_SESSION['facebook_id']))
	die("Not logged into facebook.");
$facebook_id = $_SESSION['facebook_id'];

$untold_id = $_POST["drupal_id"];
$untold_pw = $_POST["drupal_pw"];

$hash = md5($untold_pw);

$result = query_select_untold_id_with_credentials($untold_id, $hash);
if(!$result)
	die('{ "success":false, "message":"Connection to server failed." }');
$row = mysql_fetch_assoc($result);
if(!$row)
	die('{ "success":false, "message":"Please enter a valid Untold username and password." }');

$untold_id = $row['uid'];
$result = query_select_untold_id($facebook_id);
$row = mysql_fetch_assoc($result);
if($untold_id == $row['drupaluid'])
	die('{ "success":false, "message":"Already logged in on another Facebook account." }');

$result = query_insert_user($facebook_id, $untold_id);
if($result) {
	$_SESSION['untold_id'] = $untold_id;
	$_SESSION['facebook_id'] = $facebook_id;
	die('{ "success":true }');
}

die('{ "success":false, "message":"Connection to server failed." }');
?>
